<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本文将重点剖析服务调用流程，也就是消费端通过网络发起RPC服务调用时，服务提供者是如何进行服务请求响应的。 1、源码分析Dubbo服务调用流程了解过Netty网络编程的童鞋们应该知道，netty的命令处理基于ChannelHandler（事件处理链），编码、网络传输、解码、处理等，下面是关于NettyServer的初始化过程，该部分在《源码分析Dubbo网络通信篇NettyServer、Heade">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo服务调用-服务提供者如何处理请求命令与再谈Invoker">
<meta property="og:url" content="https://www.codingw.net/posts/fd487dee.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本文将重点剖析服务调用流程，也就是消费端通过网络发起RPC服务调用时，服务提供者是如何进行服务请求响应的。 1、源码分析Dubbo服务调用流程了解过Netty网络编程的童鞋们应该知道，netty的命令处理基于ChannelHandler（事件处理链），编码、网络传输、解码、处理等，下面是关于NettyServer的初始化过程，该部分在《源码分析Dubbo网络通信篇NettyServer、Heade">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdn.net/20180821120924239?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180821122113242?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="article:published_time" content="2020-11-28T11:05:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:09:25.109Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20180821120924239?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/fd487dee.html"/>





  <title>源码分析Dubbo服务调用-服务提供者如何处理请求命令与再谈Invoker | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/fd487dee.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo服务调用-服务提供者如何处理请求命令与再谈Invoker</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-28T19:05:01+08:00">
                2020-11-28
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/fd487dee.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo服务调用-服务提供者如何处理请求命令与再谈Invoker">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>本文将重点剖析服务调用流程，也就是消费端通过网络发起RPC服务调用时，服务提供者是如何进行服务请求响应的。</p>
<h2 id="1、源码分析Dubbo服务调用流程"><a href="#1、源码分析Dubbo服务调用流程" class="headerlink" title="1、源码分析Dubbo服务调用流程"></a>1、源码分析Dubbo服务调用流程</h2><p>了解过Netty网络编程的童鞋们应该知道，netty的命令处理基于ChannelHandler（事件处理链），编码、网络传输、解码、处理等，下面是关于NettyServer的初始化过程，该部分在<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/81165691">《源码分析Dubbo网络通信篇NettyServer、HeaderExchangeServer》</a>时已经讲过，本节先做一个简单的回顾：<br><img src="https://img-blog.csdn.net/20180821120924239?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"></p>
<span id="more"></span>

<p>根据服务暴露的协议，本文以dubbo协议为例：首先通过DubboProtocol通过export暴露服务时，会尝试创建关于该协议的Server服务器,服务器按ip:port进行缓存，本文重点关注ChannelHandler的包装链条，首先看一下NettyServer创建时关于Handler的绑定，代码如下：<br>NettyServer#doOpen</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">final NettyHandler nettyHandler &#x3D; new NettyHandler(getUrl(), this);</span><br><span class="line">channels &#x3D; nettyHandler.getChannels();</span><br><span class="line">&#x2F;&#x2F; https:&#x2F;&#x2F;issues.jboss.org&#x2F;browse&#x2F;NETTY-365</span><br><span class="line">&#x2F;&#x2F; https:&#x2F;&#x2F;issues.jboss.org&#x2F;browse&#x2F;NETTY-379</span><br><span class="line">&#x2F;&#x2F; final Timer timer &#x3D; new HashedWheelTimer(new NamedThreadFactory(&quot;NettyIdleTimer&quot;, true));</span><br><span class="line">bootstrap.setPipelineFactory(new ChannelPipelineFactory() &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public ChannelPipeline getPipeline() &#123;</span><br><span class="line">         NettyCodecAdapter adapter &#x3D; new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);</span><br><span class="line">         ChannelPipeline pipeline &#x3D; Channels.pipeline();</span><br><span class="line">         pipeline.addLast(&quot;decoder&quot;, adapter.getDecoder());    &#x2F;&#x2F; @start</span><br><span class="line">         pipeline.addLast(&quot;encoder&quot;, adapter.getEncoder());    </span><br><span class="line">         pipeline.addLast(&quot;handler&quot;, nettyHandler);                  &#x2F;&#x2F; @end</span><br><span class="line">         return pipeline;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>可以看出，传入Netty框架的事件处理Handler主要是3个：1、解码器；2、编码器；3、业务类NettyHandler。也就是说当服务端(Server)的读事件就绪后，进行网络读写后，会将二进制流传入解码器(Decoder)，解码出一个一个的RPC请求，然后针对每一个RPC请求，交给NettyHandler相关事件处理方法去处理，在这里传入NettyHandler的ChannelHandler为NettyServer,以网络读命令为例，最终将调用NettyServer的父类AbstractPeer的received方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line"> public void received(Channel ch, Object msg) throws RemotingException &#123;</span><br><span class="line">     if (closed) &#123;</span><br><span class="line">         return;</span><br><span class="line">     &#125;</span><br><span class="line">     handler.received(ch, msg);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>那AbstractPeer中的ChannelHandler又是“何许人也”，是通过调用NettyServer(URL url, ChannelHandler handler)中传入的，结合上图中NettyServer的构建流程，可以追溯其流程如下：</p>
<ol>
<li>DubboProtocol#createServer<br>server = Exchangers.bind(url, requestHandler);       // @1, requestHandler，为最原始的ChannelHandler，接下来整个过程都是对该handler的包装。</li>
<li>HeaderExchanger#bind<br>return new HeaderExchangeServer(Transporters.bind(url, new<br>DecodeHandler(new HeaderExchangeHandler(handler))));其包装顺序为 DecodeHandler 》HeaderExchangeHandler 》(DubboProtocol#requestHandler)</li>
<li>NettyTransporter#bind</li>
<li>NettyServer构造函数<br>super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)));这里主要包装的是事件的派发Handler，例如AllChannelHandler、ExecutionChannelHandler【Dispatch】业务Handler最终的包装顺序为：事件派发模型handler[AllChannelHandler] 》DecodeHandler 》HeaderExchangeHandler 》 DubboProtocol#requestHandler(最终的业务Handler)。结合网络Netty的处理Handler，服务端事件Handler的处理为：DubboCodec2(解码器) 》 事件派发模型handler[AllChannelHandler] 》DecodeHandler 》 HeaderExchangeHandler》 DubboProtocol#requestHandler(最终的业务Handler)。<br>上述Handler都在前面的章节中详细介绍了，接下来重点分析服务调用流程，自然需要从DubboProtocol$requestHandler入手。<br>DubboProtocol$requestHandler#recive<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public void received(Channel channel, Object message) throws RemotingException &#123;</span><br><span class="line">     if (message instanceof Invocation) &#123;</span><br><span class="line">          reply((ExchangeChannel) channel, message);</span><br><span class="line">     &#125; else &#123;</span><br><span class="line">          super.received(channel, message);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
如果是服务调用，就进入到reply方法中，否则调用父类进行请求响应。<br>DubboProtocol$requestHandler#reply<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">public Object reply(ExchangeChannel channel, Object message) throws RemotingException &#123;</span><br><span class="line">     if (message instanceof Invocation) &#123;</span><br><span class="line">          Invocation inv &#x3D; (Invocation) message;                                                &#x2F;&#x2F; @1</span><br><span class="line">          Invoker&lt;?&gt; invoker &#x3D; getInvoker(channel, inv);                                   &#x2F;&#x2F; @2</span><br><span class="line">          &#x2F;&#x2F; need to consider backward-compatibility if it&#39;s a callback</span><br><span class="line">          if (Boolean.TRUE.toString().equals(inv.getAttachments().get(IS_CALLBACK_SERVICE_INVOKE))) &#123;</span><br><span class="line">                String methodsStr &#x3D; invoker.getUrl().getParameters().get(&quot;methods&quot;);</span><br><span class="line">                boolean hasMethod &#x3D; false;</span><br><span class="line">                if (methodsStr &#x3D;&#x3D; null || methodsStr.indexOf(&quot;,&quot;) &#x3D;&#x3D; -1) &#123;</span><br><span class="line">                      hasMethod &#x3D; inv.getMethodName().equals(methodsStr);</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                     String[] methods &#x3D; methodsStr.split(&quot;,&quot;);</span><br><span class="line">                     for (String method : methods) &#123;</span><br><span class="line">                          if (inv.getMethodName().equals(method)) &#123;</span><br><span class="line">                             hasMethod &#x3D; true;</span><br><span class="line">                             break;</span><br><span class="line">                           &#125;</span><br><span class="line">                      &#125;</span><br><span class="line">                &#125;</span><br><span class="line">               if (!hasMethod) &#123;</span><br><span class="line">                   logger.warn(new IllegalStateException(&quot;The methodName &quot; + inv.getMethodName()</span><br><span class="line">                                + &quot; not found in callback service interface ,invoke will be ignored.&quot;</span><br><span class="line">                                + &quot; please update the api interface. url is:&quot;</span><br><span class="line">                                + invoker.getUrl()) + &quot; ,invocation is :&quot; + inv);</span><br><span class="line">                   return null;</span><br><span class="line">               &#125;</span><br><span class="line">          &#125;</span><br><span class="line">         RpcContext.getContext().setRemoteAddress(channel.getRemoteAddress());</span><br><span class="line">         return invoker.invoke(inv);                    &#x2F;&#x2F; @3</span><br><span class="line">   &#125;</span><br><span class="line">  throw new RemotingException(channel, &quot;Unsupported request: &quot;</span><br><span class="line">                    + (message &#x3D;&#x3D; null ? null : (message.getClass().getName() + &quot;: &quot; + message))</span><br><span class="line">                    + &quot;, channel: consumer: &quot; + channel.getRemoteAddress() + &quot; --&gt; provider: &quot; + channel.getLocalAddress());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
代码@1：获取服务调用信息，例如调用服务类名(interface)、服务方法名、参数类型，参数值。<br>代码@2：获取调用者Invoker。<br>代码@3：调用Invoker，执行具体的方法调用。<br>上述过程非常简单，但其关键点在于Invoker，那这个Invoker到底是什么呢？<br>回顾一下我们在讲解：<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/80536385">Dubbo服务提供者启动流程</a>中已提到Invoker，在本篇中我们再次对该文进行补充说明。</li>
</ol>
<h2 id="2、再谈Dubbo服务提供者暴露服务（Invoker）"><a href="#2、再谈Dubbo服务提供者暴露服务（Invoker）" class="headerlink" title="2、再谈Dubbo服务提供者暴露服务（Invoker）"></a>2、再谈Dubbo服务提供者暴露服务（Invoker）</h2><h3 id="2-1-服务提供者视角看Invoker"><a href="#2-1-服务提供者视角看Invoker" class="headerlink" title="2.1 服务提供者视角看Invoker"></a>2.1 服务提供者视角看Invoker</h3><p>我们应该记得，服务提供者在暴露服务时(export)会创建Invoker，其代码片段如下：<br>ServiceConfig#doExportUrlsFor1Protocol</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">if (registryURLs !&#x3D; null &amp;&amp; !registryURLs.isEmpty()) &#123;</span><br><span class="line">      for (URL registryURL : registryURLs) &#123;</span><br><span class="line">          url &#x3D; url.addParameterIfAbsent(Constants.DYNAMIC_KEY, registryURL.getParameter(Constants.DYNAMIC_KEY));</span><br><span class="line">          URL monitorUrl &#x3D; loadMonitor(registryURL);</span><br><span class="line">          if (monitorUrl !&#x3D; null) &#123;</span><br><span class="line">              url &#x3D; url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString());</span><br><span class="line">          &#125;</span><br><span class="line">          if (logger.isInfoEnabled()) &#123;</span><br><span class="line">               logger.info(&quot;Register dubbo service &quot; + interfaceClass.getName() + &quot; url &quot; + url + &quot; to registry &quot; + registryURL);</span><br><span class="line">          &#125;</span><br><span class="line">          Invoker&lt;?&gt; invoker &#x3D; proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString()));  &#x2F;&#x2F; @1</span><br><span class="line">          DelegateProviderMetaDataInvoker wrapperInvoker &#x3D; new DelegateProviderMetaDataInvoker(invoker, this);     &#x2F;&#x2F; @2</span><br><span class="line">          Exporter&lt;?&gt; exporter &#x3D; protocol.export(wrapperInvoker);    &#x2F;&#x2F; @3</span><br><span class="line">          exporters.add(exporter);</span><br><span class="line">       &#125;</span><br><span class="line">&#125; else &#123;</span><br><span class="line">      Invoker&lt;?&gt; invoker &#x3D; proxyFactory.getInvoker(ref, (Class) interfaceClass, url);</span><br><span class="line">      DelegateProviderMetaDataInvoker wrapperInvoker &#x3D; new DelegateProviderMetaDataInvoker(invoker, this);</span><br><span class="line">      Exporter&lt;?&gt; exporter &#x3D; protocol.export(wrapperInvoker);</span><br><span class="line">      exporters.add(exporter);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：根据&lt;dubbo:service ref = “interfaceImpl” interface = “”  /&gt; 首先获取ref的代理对象，真正的服务实现类proxy，然后通过proxyFactory【JavassistProxyFactory、JdkProxyFactory】创建最原始的Invoker，即AbstractProxyInvoker，使用的是匿名实现类，即提供反射方式进行方法的调用。<br><img src="https://img-blog.csdn.net/20180821122113242?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>从abstract Object doInvoker(T proxy, String methodName, Class&lt; ? &gt;[] parameterTypes, Object[] arguments) 可以最终是通过对象发射方式进行方法调用。</p>
<p>代码@2：首先使用DelegateProviderMetaDataInvoker对AbstractProxyInvoker进行包装，主要是将ServerConfig对象与Invoker一起保存。</p>
<p>代码@3：根据具体协议对服务端Invoker进行导出（继续包装）。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">registry:&#x2F;&#x2F;127.0.0.1:2181&#x2F;com.alibaba.dubbo.registry.RegistryService?application&#x3D;demo-provider&amp;dubbo&#x3D;2.0.0&amp;export&#x3D;dubbo%3A%2F%2F192.168.56.1%3A20880%2Fcom.alibaba.dubbo.demo.DemoService%3Fanyhost%3Dtrue%26application%3Ddemo-provider%26bind.ip%3D192.168.56.1%26bind.port%3D20880%26dubbo%3D2.0.0%26generic%3Dfalse%26interface%3Dcom.alibaba.dubbo.demo.DemoService%26methods%3DsayHello%26pid%3D14360%26qos.port%3D22222%26side%3Dprovider%26stub%3Dcom.alibaba.dubbo.demo.provider.DemoServiceStub%26timestamp%3D1533944510702&amp;pid&#x3D;14360&amp;qos.port&#x3D;22222&amp;registry&#x3D;zookeeper&amp;timestamp&#x3D;1533944510687</span><br></pre></td></tr></table></figure>
<p>协议前缀:registry，故根据SPI机制，具体的协议为RegistryProtocol。<br>registry=zookeeper ：代表注册中心使用zookeeper，在连接注册中心时根据该值进行策略选择。export= dubbo://…   :  根据export，在服务端按照协议启动对应的服务端程序，该协议注意指定请求包的二进制协议，例如协议头和协议体。</p>
<p>按照registry协议，应该会直接调用RegistryProtocol#export，但我们忽略了Dubbo的另一机制，该部分也是在<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/80536385">服务提供者启动流程</a>中被遗漏。Dubbo为了对服务调用进行包装，采用了过滤器Filter 链模式，在AbstractProxyInvoker调用之前，先执行一系列的过滤器Filter，Dubbo协议默认的协议层面的过滤器代理实现为：com.alibaba.dubbo.rpc.protocol.ProtocolListenerWrapper,SPI定义文件见：<br>dubbo-rpc-api/src/main/resources/METAINF/dubbo/internal/com.alibaba.dubbo.rpc.Pr<br>otocol：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">filter&#x3D;com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper</span><br><span class="line">listener&#x3D;com.alibaba.dubbo.rpc.protocol.ProtocolListenerWrapper</span><br><span class="line">mock&#x3D;com.alibaba.dubbo.rpc.support.MockProtocol</span><br></pre></td></tr></table></figure>
<p>ProtocolFilterWrapper#export</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public &lt;T&gt; Exporter&lt;T&gt; export(Invoker&lt;T&gt; invoker) throws RpcException &#123;</span><br><span class="line">     if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) &#123;     &#x2F;&#x2F; @1</span><br><span class="line">        return protocol.export(invoker);</span><br><span class="line">     &#125;</span><br><span class="line">     return protocol.export(buildInvokerChain(invoker, Constants.SERVICE_FILTER_KEY, Constants.PROVIDER));    &#x2F;&#x2F; @2</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：如果协议为registry，则直接调用RegistryProtocol#expoert完成协议导出，协议为registry其含义是通过注册中心暴露，最终会根据expoert，调用具体的协议进行服务暴露，最终会再次进入该方法。<br>代码@2：如果为具体协议，例如dubbo等，则通过buildInvokerChain构建Invoker链。<br>ProtocolFilterWrapper#buildInvokerChain</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">private static &lt;T&gt; Invoker&lt;T&gt; buildInvokerChain(final Invoker&lt;T&gt; invoker, String key, String group) &#123;</span><br><span class="line">        Invoker&lt;T&gt; last &#x3D; invoker;</span><br><span class="line">        List&lt;Filter&gt; filters &#x3D; ExtensionLoader.getExtensionLoader(Filter.class).getActivateExtension(invoker.getUrl(), key, group);    &#x2F;&#x2F; @1</span><br><span class="line">        if (!filters.isEmpty()) &#123;</span><br><span class="line">            for (int i &#x3D; filters.size() - 1; i &gt;&#x3D; 0; i--) &#123;</span><br><span class="line">                final Filter filter &#x3D; filters.get(i);</span><br><span class="line">                final Invoker&lt;T&gt; next &#x3D; last;</span><br><span class="line">                last &#x3D; new Invoker&lt;T&gt;() &#123;       &#x2F;&#x2F; @2</span><br><span class="line"></span><br><span class="line">                    @Override</span><br><span class="line">                    public Class&lt;T&gt; getInterface() &#123;</span><br><span class="line">                        return invoker.getInterface();</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    @Override</span><br><span class="line">                    public URL getUrl() &#123;</span><br><span class="line">                        return invoker.getUrl();</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    @Override</span><br><span class="line">                    public boolean isAvailable() &#123;</span><br><span class="line">                        return invoker.isAvailable();</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    @Override</span><br><span class="line">                    public Result invoke(Invocation invocation) throws RpcException &#123;</span><br><span class="line">                        return filter.invoke(next, invocation);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    @Override</span><br><span class="line">                    public void destroy() &#123;</span><br><span class="line">                        invoker.destroy();</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    @Override</span><br><span class="line">                    public String toString() &#123;</span><br><span class="line">                        return invoker.toString();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return last;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：加载系统配置的所有Filer，并根据作用对象（服务提供者、服务消费者），返回合适的Filter链表。、</p>
<p>代码@2：根据Filter构建Invoker链。<br>Dubbo默认提供的Filter在dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter中定义，其内容为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">echo&#x3D;com.alibaba.dubbo.rpc.filter.EchoFilter</span><br><span class="line">generic&#x3D;com.alibaba.dubbo.rpc.filter.GenericFilter</span><br><span class="line">genericimpl&#x3D;com.alibaba.dubbo.rpc.filter.GenericImplFilter</span><br><span class="line">token&#x3D;com.alibaba.dubbo.rpc.filter.TokenFilter</span><br><span class="line">accesslog&#x3D;com.alibaba.dubbo.rpc.filter.AccessLogFilter</span><br><span class="line">activelimit&#x3D;com.alibaba.dubbo.rpc.filter.ActiveLimitFilter</span><br><span class="line">classloader&#x3D;com.alibaba.dubbo.rpc.filter.ClassLoaderFilter</span><br><span class="line">context&#x3D;com.alibaba.dubbo.rpc.filter.ContextFilter</span><br><span class="line">consumercontext&#x3D;com.alibaba.dubbo.rpc.filter.ConsumerContextFilter</span><br><span class="line">exception&#x3D;com.alibaba.dubbo.rpc.filter.ExceptionFilter</span><br><span class="line">executelimit&#x3D;com.alibaba.dubbo.rpc.filter.ExecuteLimitFilter</span><br><span class="line">deprecated&#x3D;com.alibaba.dubbo.rpc.filter.DeprecatedFilter</span><br><span class="line">compatible&#x3D;com.alibaba.dubbo.rpc.filter.CompatibleFilter</span><br><span class="line">timeout&#x3D;com.alibaba.dubbo.rpc.filter.TimeoutFilter</span><br></pre></td></tr></table></figure>
<p>当然这些过滤器并不全是服务提供者端的，每个过滤器通过@Activate注解来定义属于服务端还是消费端。<br>Dubbo还为服务暴露(export)和服务引用(reference)提供了事件回调通知，其实现与Filter类似，其实现类为：com.alibaba.dubbo.rpc.protocol.ProtocolListenerWrapper,其事件只是在服务expoert、或服务reference时执行，与调用执行的Filter不一样，因为是针对服务暴露与服务引用的事件。<br>DubboCodec2(解码器) 》 事件派发模型handler[AllChannelHandler] 》 DecodeHandler  》  HeaderExchangeHandler 》 DubboProtocol#requestHandler(最终的业务Handler) 》Filter Chain 》AbstractProxyInvoker(JavassistProxyFactory#getInvoker),通过反射进行服务端方法调用。</p>
<h3 id="2-2-从消费端的视角看Invoker"><a href="#2-2-从消费端的视角看Invoker" class="headerlink" title="2.2 从消费端的视角看Invoker"></a>2.2 从消费端的视角看Invoker</h3><p>从消费者的视角看Invoker，即我们常说的服务调用器，结合集群容错功能的Invoker,服务调用的门面（同一封装），例如DubboInvoker，根据dubbo协议，封装服务调用请求并通过网络向服务器发送请求包。其主要子类为AbstractInvoker、AbstractClusterInvoker（集群模式）。消费端服务发起请求时，同样会被ProtocolFilterWrapper拦截，引入调用链（获取消费端的Filter Chain）。关于消费端的Invoker，请大家参考如下两篇博文：<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/80963998">Dubbo集群容错模式</a><br><a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/80642774">Dubbo Invoker概述</a><br><a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/80621535">Dubbo消费者启动流程</a></p>
<p>综上所述，服务端的Invoker职责通过反射机制，根据服务名、方法名、参数调用方法完成服务端的响应，其类主要为com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker，客户端的Invoker职责主要是按照协议组织请求包，通过网络发送服务调用请求，其代表为AbstractInvoker、AbstractClusterInvoker。<br>服务调用的整体流程就介绍到这里了，从下一篇开始，将重点分析Dubbo Filter机制。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/4fb5ca23.html" rel="next" title="源码分析Dubbo监控中心实现原理">
                <i class="fa fa-chevron-left"></i> 源码分析Dubbo监控中心实现原理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/1ea63fb8.html" rel="prev" title="源码分析Dubbo服务提供者、服务消费者并发度控制机制">
                源码分析Dubbo服务提供者、服务消费者并发度控制机制 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90Dubbo%E6%9C%8D%E5%8A%A1%E8%B0%83%E7%94%A8%E6%B5%81%E7%A8%8B"><span class="nav-number">1.</span> <span class="nav-text">1、源码分析Dubbo服务调用流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E5%86%8D%E8%B0%88Dubbo%E6%9C%8D%E5%8A%A1%E6%8F%90%E4%BE%9B%E8%80%85%E6%9A%B4%E9%9C%B2%E6%9C%8D%E5%8A%A1%EF%BC%88Invoker%EF%BC%89"><span class="nav-number">2.</span> <span class="nav-text">2、再谈Dubbo服务提供者暴露服务（Invoker）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E6%9C%8D%E5%8A%A1%E6%8F%90%E4%BE%9B%E8%80%85%E8%A7%86%E8%A7%92%E7%9C%8BInvoker"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 服务提供者视角看Invoker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E4%BB%8E%E6%B6%88%E8%B4%B9%E7%AB%AF%E7%9A%84%E8%A7%86%E8%A7%92%E7%9C%8BInvoker"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 从消费端的视角看Invoker</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
